﻿using System.Data;
using System.IO;
using System.Text;
using ZeBobo5.LibraryHelper.Core.Sql;

namespace ZeBobo5.LibraryHelper.Orm
{
    public class OrmDataElementGenerator
    {
        private const string fieldSchema = @"public static OrmField<{0}, {2}> {1} = new OrmField<{0}, {2}>(""{1}"", {3});";
        private const string propertySchema = @"public OrmValues<{0}> {1} {{ get {{ return Fields.{1}.Values(this); }} }}";


        public static void Generate(string connectionName, string tableName)
        {
            DataTable table = SqlHelper.ExecQueryToDataTable(connectionName, string.Format("SELECT * FROM {0}", tableName));
            FileStream fs = new FileStream(string.Format("{0}.cs", tableName), FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(Get(table, tableName));
            sw.Flush();
            sw.Close();
        }

        private static string Get(DataTable table, string tableName)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("using ZeBobo5.LibraryHelper.Orm;");
            sb.AppendFormat("public partial class {0} : OrmDataElementBase<{0}>", tableName.ToUpper()).AppendLine();
            sb.AppendLine("{");
            foreach (DataColumn column in table.Columns)
            {
                if (column.AllowDBNull)
                {
                    sb.AppendLine(string.Format(propertySchema, string.Format("Nullable<{0}>", column.DataType.Name), column.ColumnName.ToUpper()));
                }
                else
                {
                    sb.AppendLine(string.Format(propertySchema, column.DataType.Name, column.ColumnName.ToUpper()));
                }
            }
            sb.AppendLine("public class Fields");
            sb.AppendLine("{");

            foreach (DataColumn column in table.Columns)
            {
                if (column.AllowDBNull && column.DataType.Name.ToLower() != "string")
                {
                    sb.AppendLine(string.Format(fieldSchema, tableName.ToUpper(), column.ColumnName.ToUpper(), string.Format("Nullable<{0}>", column.DataType.Name), "null"));
                }
                else if (column.DataType.Name.ToLower() == "string")
                {
                    sb.AppendLine(string.Format(fieldSchema, tableName.ToUpper(), column.ColumnName.ToUpper(), "string", "\"\""));
                }
                else
                {
                    sb.AppendLine(string.Format(fieldSchema, tableName.ToUpper(), column.ColumnName.ToUpper(), column.DataType.Name, "0"));
                }
            }

            sb.AppendLine("}");
            sb.AppendLine("}");
            return sb.ToString();
        }
    }
}